package db

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"server_cluster/chat/chat_config"
	"time"
)

var Conn *gorm.DB

func InitDB() error {
	var err error
	dbuser := chat_config.DBUSER_PROD
	if chat_config.CONF.DEV_ENV {
		dbuser = chat_config.DBUSER_DEV
	}
	Conn, err = gorm.Open(mysql.Open(dbuser + chat_config.CONF.DBHOST), &gorm.Config{})
	if err != nil {
		log.Println(err)
		return err
	}
	sqlDB, err := Conn.DB()
	if err != nil {
		log.Println(err)
		return err
	}
	sqlDB.SetMaxOpenConns(chat_config.CONF.DBPOOL)
	sqlDB.SetMaxIdleConns(chat_config.CONF.DBPOOL)
	sqlDB.SetConnMaxLifetime(60 * time.Second)
	return nil
}
